<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/gc.js"></script>
<script src="../../../resources/js-test.js"></script>
<script src='../resources/worker-util.js'></script>
</script>
<body>
<script>
description('Verify that creation of a worker does not leak its creating document.');

window.jsTestIsAsync = true;

function log(message)
{
    document.getElementById("console").innerHTML += message + "<br>";
}

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

// Set this number as high as possible without introducing timeouts in debug builds.
// Reducing it does not require rebaselines.
var numIterations = 6;

var currentIteration = 0;
var iframe = null;
var numLiveAtStart = 0;
var numLiveAtEnd = 0;

window.onmessage = function(event) {
    if (event.data == "done") {
        runOneIteration();
    }
};

function startTest()
{
    gc();
    if (window.internals && internals.numberOfLiveDocuments) {
        numLiveAtStart = internals.numberOfLiveDocuments();
        // Depending on which tests ran before this one in DumpRenderTree,
        // their Document instances may not have been fully cleaned up yet.
        // When this test is run in isolation, there should be only one
        // live document at this point.
        runOneIteration();
    } else {
        debug("internals.numberOfLiveDocuments not available -- no point in running test");
        finishTest();
    }
}

function runOneIteration() {
    if (currentIteration < numIterations) {
        ++currentIteration;

        var createdIframe = false;
        if (!iframe) {
            iframe = document.createElement("iframe");
            createdIframe = true;
        }
        iframe.setAttribute("src", "resources/worker-document-leak-iframe.html");
        if (createdIframe)
            document.body.appendChild(iframe);
        return;
    }
    asyncGC(finishTest);
}

function finishTest()
{
    gc();

    if (window.internals && internals.numberOfLiveDocuments) {
        numLiveAtEnd = internals.numberOfLiveDocuments();
        // Under no circumstances should the number of live documents
        // at the end be more than 1 greater than the number at the
        // beginning (because of the iframe).
        if (numLiveAtEnd > numLiveAtStart + 1) {
            testFailed("leaked documents during test run (started with " + numLiveAtStart + ", ended with " + numLiveAtEnd + ")");
        } else {
            testPassed("did not leak documents during test run");
        }
    }
    finishJSTest();
}

window.onload = startTest;
</script>
</body>
</html>
